﻿// ==============================================================================
// Copyright (c) 2010 Bndy.Net, All rights reserved.
// Created by Bndy at 5/8/2010 3:46:23 PM
//
//                    * * * * * * * * * * * * * 
//                    * Mail- bndy5337@163.com *
//                    * Msn - bndy5337@msn.com *
//                    * * * * * * * * * * * * * 
//
// ------------------------------------------------------------------------------
// Jquery Plug-in。
// ==============================================================================

/****************************** Common Functions *******************************/

// 将Json对象转为字符串
function JsonToStr(o) {
    var arr = [];
    var fmt = function (s) {
        if (typeof s == 'object' && s != null) return JsonToStr(s);
        return /^(string|number)$/.test(typeof s) ? "'" + s + "'" : s;
    }
    for (var i in o) arr.push("'" + i + "':" + fmt(o[i]));
    return '{' + arr.join(',') + '}';
}

// 设置样式。styleContent 为 style 字符串或如“class:className”
function setSkin(ele, styleContent) {
    if (styleContent.indexOf("class:") >= 0) {
        var content = styleContent.split("class:")[1];
        $(ele).addClass(content);
    }
    else {
        $(ele).attr("style", styleContent);
    }
}

// 清除样式。styleContent 为 style 字符串或如“class:className”
function clearSkin(ele, styleContent) {
    if (styleContent.indexOf("class:") >= 0) {
        var content = styleContent.split("class:")[1];
        $(ele).removeClass(content);
    }
    else {
        $(ele).removeAttr("style");
    }
}

/******************************** Jquery Plug-in *******************************/

// 浮动层
jQuery.fn.__float = function (location) {
    //判断浏览器版本
    var isIE6 = false;
    var Sys = {};
    var ua = navigator.userAgent.toLowerCase();
    var s;
    (s = ua.match(/msie ([\d.]+)/)) ? Sys.ie = s[1] : 0;
    if (Sys.ie && Sys.ie == "6.0") {
        isIE6 = true;
    }
    var windowWidth, windowHeight; //窗口的高和宽

    //取得窗口的高和宽
    if (self.innerHeight) {
        windowWidth = self.innerWidth;
        windowHeight = self.innerHeight;
    } else if (document.documentElement && document.documentElement.clientHeight) {
        windowWidth = document.documentElement.clientWidth;
        windowHeight = document.documentElement.clientHeight;
    } else if (document.body) {
        windowWidth = document.body.clientWidth;
        windowHeight = document.body.clientHeight;
    }

    return this.each(function () {
        var loc; //层的绝对定位位置
        if (location == undefined || location.constructor == String) {
            switch (location) {
                case ("rightbottom"): //右下角
                    loc = { right: "0px", bottom: "0px" };
                    break;
                case ("leftbottom"): //左下角
                    loc = { left: "0px", bottom: "0px" };
                    break;
                case ("lefttop"): //左上角
                    loc = { left: "0px", top: "0px" };
                    break;
                case ("righttop"): //右上角
                    loc = { right: "0px", top: "0px" };
                    break;
                case ("middletop"): //居中置顶
                    loc = { left: windowWidth / 2 - $(this).width() / 2 + "px", top: "0px" };
                    break;
                case ("middlebottom"): //居中置低
                    loc = { left: windowWidth / 2 - $(this).width() / 2 + "px", bottom: "0px" };
                    break;
                case ("leftmiddle"): //左边居中
                    loc = { left: "0px", top: windowHeight / 2 - $(this).height() / 2 + "px" };
                    break;
                case ("rightmiddle"): //右边居中
                    loc = { right: "0px", top: windowHeight / 2 - $(this).height() / 2 + "px" };
                    break;
                case ("middle"): //居中
                    var l = 0; //居左
                    var t = 0; //居上
                    l = windowWidth / 2 - $(this).width() / 2;
                    t = windowHeight / 2 - $(this).height() / 2;
                    loc = { left: l + "px", top: t + "px" };
                    break;
                default: //默认为右下角
                    location = "rightbottom";
                    loc = { right: "0px", bottom: "0px" };
                    break;
            }
        } else {
            loc = location;
        }
        var wrap = $("<div></div>");
        /*fied ie6 css hack*/
        if (isIE6) { wrap = $("<div style=\"top:expression(documentElement.scrollTop+documentElement.clientHeight-this.offsetHeight);\"></div>"); }

        $("body").append(wrap);
        wrap.css(loc).css({ position: "fixed",
            z_index: "999"
        });
        /*fied ie6 css hack */
        if (isIE6) {
            wrap.css("position", "absolute");
            $("body").css("background-attachment", "fixed");
        }
        //将要固定的层添加到固定层里
        $(this).appendTo(wrap);
    });
};

// 全选
jQuery.fn.__checkAll = function (idPrefix) {
    $(this).click(function () {
        $("input[type=checkbox][id^=" + idPrefix + "]").each(
            function () {
                this.checked = true;
            }
        );
    });
};

// 取消全选
jQuery.fn.__descheckAll = function (idPrefix) {
    $(this).click(function () {
        $("input[type=checkbox][id^=" + idPrefix + "]").each(function () { this.checked = true; });
    });
};

// 全选/取消全选
jQuery.fn.__toggleCheck = function (idPrefix) {
    var c = false;
    $(this).click(function () {
        if (c) c = false;
        else c = true;
        $("input[type=checkbox][id^=" + idPrefix + "]").each(
            function () {
                this.checked = c;
            }
        );
    });
};

// 设置数据绑定控件的样式及鼠标经过事件
jQuery.fn.__setRepeaterStyle = function (itemTag, evenStyle, hoverStyle) {
    $("#" + this.attr("id") + " " + itemTag + ":odd").addClass(evenStyle);
    var cssOriginal = "";
    $("#" + this.attr("id") + " " + itemTag + "").mouseover(function () {
        cssOriginal = $(this).attr("class");
        $(this).addClass(hoverStyle);
    });

    $("#" + this.attr("id") + " " + itemTag + "").mouseout(function () {
        $(this).removeClass();
        if (cssOriginal.length > 0) {
            $(this).addClass(cssOriginal);
        }
    });
};

// 下拉菜单, 暂只支持IE浏览器。
jQuery.fn.__popMenu = function (menuID) {
    var isClicked = false;
    var wrap = $("<div></div>");

    return this.each(function () {
        $(this).click(function () {
            var position = $(this).position();
            var width = $(this).width();
            var height = $(this).height();
            if (isClicked) {
                isClicked = false;
                wrap.empty();
                return
            }
            else {
                isClicked = true;
                wrap.html($("#" + menuID).html());
                $(this).append(wrap);
                wrap.css({ position: "absolute", left: position.left, top: position.top + height, width: width, height: height });
                return;
            }
        });
    });
};

// 遮蔽层
jQuery.fn.__maskLayer = function () {
    var layer = $("<div id='maskLayer'></div>");
    //取得窗口的高和宽
    var m_windowWidth, m_windowHeight;
    if (self.innerHeight) {
        m_windowWidth = self.innerWidth;
        m_windowHeight = self.innerHeight;
    } else if (document.documentElement && document.documentElement.clientHeight) {
        m_windowWidth = document.documentElement.clientWidth;
        m_windowHeight = document.documentElement.clientHeight;
    } else if (document.body) {
        m_windowWidth = document.body.clientWidth;
        m_windowHeight = document.body.clientHeight;
    }

    layer.css({ position: "absolute", left: "0px", top: "0px", width: m_windowWidth, height: m_windowHeight, background: "#dedede", opacity: "0.6", filter: "Alpha(Opacity=60)" });
    layer.click(function () {
        layer.css({ display: "none" });
    });
    $("body").append(layer);
};

// Ajax 执行WebService。
jQuery.fn.__ajaxWebService = function (url, data, fnSuccess) {
    $.ajax({
        type: "POST",
        contentType: "application/json",
        url: url,
        data: data,
        dataType: "json",
        success: fnSuccess
    });
    alert(url);
};

// 通过Ajax加载用户控件。此方法只限asp.net
jQuery.fn.__loadUserControl = function (control, page) {
    var $dom = this;
    if (page == "" || page == null) {
        page = location.pathname.replace("/", "");
    }
    page += "/LoadUserControl";
    jQuery.fn.__ajaxWebService(page, "{control:'" + control + "'}", function (data) { alert("Here it's result:" + data.d); $dom.html(data.d); });
};

// 创建Table行
jQuery.fn.__newTableRow = function () {
    var row = document.createElement("tr");
    for (var i = 0; i < arguments.length; i++) {
        var item = arguments[i];
        var data;
        var style;
        var col = document.createElement("td");
        if (item.split("|").length > 0) {
            data = item.split("|")[0];
            style = item.split("|")[1];
            col.setAttribute("style", style);
            col.style.cssText = style;  // 兼容IE
        }
        else {
            data = o.toString();
        }
        col.appendChild(document.createTextNode(data));
        row.appendChild(col);
    }

    $(this).append(row);
};

// 设置当前列表项目。
// currentArgument  当前项的值，如ID等。
// relativeSelector 当前项值的选择器（相对于项Tag,如“tr>td:text”、“tr>td>input:val”）
// styleContent     样式字符串或class。如“font-weight:bold;”或 “class:className”
jQuery.fn.__selectedItem = function (currentArgument, relativeSelector, styleContent, handler) {
    var arr = relativeSelector.split(">");
    var depth = arr.length;
    var itemTag = arr[0];
    var valType = arr[arr.length - 1].indexOf(":") > 0 ? arr[arr.length - 1].split(":")[1] : "text";
    var selector = relativeSelector.replace(itemTag + ">", "").replace(":" + valType, "");

    $("#Tbl").find(itemTag).each(function () {
        var val = eval("$(this).find(selector + \":first\")." + valType + "()");
        if (val == currentArgument.toString()) {
            setSkin($(this), styleContent);
        }
        else {
            clearSkin($(this), styleContent);
        }
    });

    // handle some things...
    if (handler != null) {
        hanlder();
    }
};

// 创建下级下拉列表
jQuery.fn.__createNewDropDownList = function (valContainerID, data) {
    var ddlID = "ddl_" + valContainerID;
    $(this).change(function () {
        var ddl;

        // 判断元素是否存在
        if ($("#" + ddlID).length > 0) {
            ddl = $("#" + ddlID);
            ddl.html("");
        }
        else {
            ddl = $("<select id=\"" + ddlID + "\" onchange=\"$('#" + valContainerID + "').val(this.value);alert($('#" + valContainerID + "').val());\" />");
            $(this).parent().append($(ddl));
        }

        var items = data.split(",");
        for (var i = 0; i < items.length; i++) {
            if (items[i] != "") {
                var item = items[i].split("|");
                var val = item[0];
                var text = item[0];
                if (item.length > 1) {
                    var text = item[1];
                }

                var opt = $("<option value=\"" + val + "\">" + text + "</option>");
                $(ddl).append(opt);
            }
        }

        return ddl;
    });
};
